import Vue from 'vue'

import config from './config'
import axios from 'axios'

const utils = {
	// 判断请求是否成功
	isSuccess: function(res) {
		let data = res && res.data
		if (data && "success" === data.status) {
			return true
		}
		return false
	},
	// 返回的响应状态数据
	getResponse: function(res) {
		return (res && res.data) || {}
	},
	// 在响应成功的情况下返回数据
	getResponseData: function(res) {
		let resData = res && res.data
		if (resData && "success" === resData.status) {
			return resData.data
		}
		return null
	},
	// 判断用户是否有角色
	hasRole: function(role) {
		let userInfo = localStorage.getItem(config.userInfoName)
		let authorities = userInfo && userInfo.authorities || []
		authorities.forEach(r => {if (role == r) return true})
		return false
	},
	// 判断是否为超级管理员
	isSuperAdmin: function() {
		return this.hasRole(config.rolePrefix + "SUPERADMIN")
	},
	// 是否为租户
	isTenant: function() {
		let userInfo = localStorage.getItem(config.userInfoName)
		let isT = userInfo && userInfo.user && userInfo.user.isTenant
		return 'Y' === isT
	},
	// 获取内存中当前登录用户信息
	getLoginUser: function() {
		return localStorage.getItem(config.userInfoName) || {}
	},
	// 注销登出
	logout: function() {
		axios.post("/admin/sys/logout").then(res => {
			if (this.isSuccess(res)) {
				localStorage.removeItem("token")
				app.$router.replace({
					name: "login"
				})
			}
		})
	},
	// 将对象数组转换成属性数组
	getPropertyArrayFromObjectArray: function(objArray, p) {
		let properties = []
		objArray.forEach(function(obj) {
			properties.push(obj[p])
		});
		return properties
	},
	// 将对象数组中的对象的某两个属性值抽出形成一个对象
	getObjectFromObjectArray: function(objArray, key, value) {
		let object = {}
		objArray.forEach(obj => {
			// 将对象的key属性的值作为键，将value属性值作为值
			object[obj[key]] = obj[value]
		});
		return object
	},
	// 表单对象属性的复制
	copyFormObject: function(source, target) {
		for (let p in source) {
			target[p] = source[p]
		}
	},
	// 格式化日期小于10在前面补0
	formatDateNumber: function(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	},
	// 格式化日期字符串
	formatDate: function(date) {
		if (date) {
			const year = date.getFullYear()
			const month = date.getMonth() + 1
			const day = date.getDate()
			return [year, month, day].map(this.formatDateNumber).join('-')
		}
	},
	// 获取当前年份
	getCurrentYear: function() {
		let date = new Date()
		return date.getFullYear()
	},
	// 获取当前月份
	getCurrentMonth: function() {
		let date = new Date()
		return date.getMonth() + 1
	},
	//是否为空
	isNullOrEmpty: function(value) {
		return (value === null || value === '' || value === undefined) ? true : false;
	},
	//去首尾空格
	trim: function(value) {
		return value.replace(/(^\s*)|(\s*$)/g, "");
	},
	//是否为手机号
	isMobile: function(value) {
		return /^(?:13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{5}(\d{3}|\*{3})$/.test(value);
	},
	//金额，只允许保留两位小数
	isFloat: function(value) {
		return /^([0-9]*[.]?[0-9])[0-9]{0,1}$/.test(value);
	},
	//数值
	isDecimal: function(value) {
		return /^([0-9]*[.]?[0-9])[0-9]{0,}$/.test(value);
	},
	//是否全为数字
	isNum: function(value) {
		return /^[0-9]+$/.test(value);
	},
	//密码为8~20位数字和字母组合
	checkPwd: function(value) {
		return /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/.test(value);
	},
	//格式化手机号码
	formatNum: function(num) {
		if (utils.isMobile(num)) {
			num = num.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
		}
		return num;
	},
	//金额格式化
	rmoney: function(money) {
		return parseFloat(money).toFixed(2).toString().split('').reverse().join('').replace(/(\d{3})/g, '$1,').replace(
			/\,$/, '').split('').reverse().join('');
	},
	//日期格式化
	formatDateTime: function(formatStr, fdate) {
		if (fdate) {
			if (~fdate.indexOf('.')) {
				fdate = fdate.substring(0, fdate.indexOf('.'));
			}
			fdate = fdate.toString().replace('T', ' ').replace(/\-/g, '/');
			var fTime, fStr = 'ymdhis';
			if (!formatStr)
				formatStr = "y-m-d h:i:s";
			if (fdate)
				fTime = new Date(fdate);
			else
				fTime = new Date();
			var month = fTime.getMonth() + 1;
			var day = fTime.getDate();
			var hours = fTime.getHours();
			var minu = fTime.getMinutes();
			var second = fTime.getSeconds();
			month = month < 10 ? '0' + month : month;
			day = day < 10 ? '0' + day : day;
			hours = hours < 10 ? ('0' + hours) : hours;
			minu = minu < 10 ? '0' + minu : minu;
			second = second < 10 ? '0' + second : second;
			var formatArr = [
				fTime.getFullYear().toString(),
				month.toString(),
				day.toString(),
				hours.toString(),
				minu.toString(),
				second.toString()
			]
			for (var i = 0; i < formatArr.length; i++) {
				formatStr = formatStr.replace(fStr.charAt(i), formatArr[i]);
			}
			return formatStr;
		} else {
			return "";
		}
	},
	// 另存为文本文件
	saveTextToFile: function(content, fileName){
		let aEle = document.createElement("a");
		let blob = new Blob([content]); 
		aEle.download = fileName;
		aEle.href = URL.createObjectURL(blob);
		aEle.click();
	}
}

Vue.prototype.$utils = utils

export default utils
